package com.xinchengxd.user.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.*;
import com.auth0.jwt.impl.JWTParser;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;
import com.xinchengxd.commons.ResponseResult;
import com.xinchengxd.user.entity.User;
import com.xinchengxd.user.mapper.UserMapper;
import com.xinchengxd.user.service.UserService;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author: 姚新成
 * @Date: 2021/11/8:15:18
 * @Description:
 */

@Service
public class UserServiceImpl implements UserService {
    @Resource
    UserMapper userMapper;
    @Override
    public int add(User user) {
        user.setRegTime(new Date());
        int add = userMapper.add(user);
        return add;
    }

    @Override
    public ResponseResult<String> sign(User user) {
        User resUser = userMapper.sign(user);
        System.out.println("resUser:" + resUser);

        if(resUser==null){
            return new ResponseResult<String>(500,"查询失败",null);
        }
        /*token*/
        String[] userInfo = new String[2];
        userInfo[0]=resUser.getAccount();
        userInfo[1]= String.valueOf(resUser.getId());
        Long expireSecond = 60L * 30L; //过期时间为半小时
        Date expireTime = DateUtils.addSeconds(new Date(),expireSecond.intValue());
        System.out.println("过期date:"+expireTime);
        String salt = "xinchengdd";//盐
        Algorithm algorithm = Algorithm.HMAC256(salt);//加密后的盐
        System.out.println("加密的盐为："+algorithm.getName());

        /*生成token*/
        String JWTid = UUID.randomUUID().toString();
        String Token = JWT.create()
                .withArrayClaim("myToken",userInfo)
                //jwt唯一id
                .withJWTId(JWTid)
                //现在时间
                .withIssuedAt(new Date())
                //过期时间
                .withExpiresAt(expireTime)
                //签名/盐
                .sign(algorithm);

        return new ResponseResult<String>(200,"登录成功", Token);
    }

    @Override
    public ResponseResult<String> verifyToken(String token) {

        System.out.println("token校验页面：");
        String salt = "xinchengdd";//盐
        Algorithm algorithm = Algorithm.HMAC256(salt);//加密后的盐

        System.out.println("token:" + token);
        Verification require = JWT.require(algorithm);
        JWTVerifier build = require.build();
        System.out.println("require:" + require + "..." + "build:" + build);
        /*使用传入的token进行验证*/
        ResponseResult<String> res = new ResponseResult<>(505,"请求已送达","");
        DecodedJWT verify = null;
        try {
            if(token==null||token.trim().isEmpty()){
                res.setData("没有token");
                return res;
            }
            verify = build.verify(token);
        } catch (AlgorithmMismatchException | SignatureVerificationException |InvalidClaimException e) {
            res.setData("token错误");
            return  res;
        } catch (TokenExpiredException e) {
            res.setData("token过期");
            return res;
        }


        System.out.println("DecodeJWT" + verify.toString());
        System.out.println(verify.getHeader() +
                "\n" + verify.getAlgorithm() +
                "\n" + verify.getSignature() +
                "\n" + verify.getToken() +
                "\n" + verify.getKeyId() +
                "\n" + verify.getClaim("myToken") +
                "\n" + verify.getClaims().toString());

        String[] myTokens = verify.getClaim("myToken").asArray(String.class);
        res.setData(myTokens[1]);
        res.setCode(200);
        return res;
    }

    @Override
    public User look(Integer id) {
        return userMapper.look(id);
    }

    @Override
    public void update(User user) {
        userMapper.update(user);
    }

    @Override
    public ResponseResult<String> updateForPassword(String oldPwd,String newPwd ,Integer id) {
        User look = userMapper.look(id);
        if(look.getPassword().equals(oldPwd)){
            userMapper.updateForPassword(newPwd,id);
            return new ResponseResult<>(200,"成功","修改完成");
        }else{
            return new ResponseResult<>(601,"失败","原密码输入错误");
        }

    }

    @Override
    public int changePoint(Integer id, Integer change) {
        User look = userMapper.look(id);
        change += look.getPoint();
        return userMapper.changePoint(id,change);
    }


}
